package com.ly.friend.service.user.Impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ly.common.core.constants.Constants;
import com.ly.common.core.domain.TableDataInfo;
import com.ly.common.core.enums.ExamListType;
import com.ly.common.core.enums.ResultCode;
import com.ly.common.core.utils.ThreadLocalUtil;
import com.ly.common.security.exception.ServiceException;
import com.ly.common.security.service.TokenService;
import com.ly.friend.domain.exam.Exam;
import com.ly.friend.domain.exam.dto.ExamQueryDTO;
import com.ly.friend.domain.exam.vo.ExamVO;
import com.ly.friend.domain.user.UserExam;
import com.ly.friend.domain.user.VO.UserVO;
import com.ly.friend.manager.exam.ExamCacheManager;
import com.ly.friend.manager.user.UserCacheManager;
import com.ly.friend.mapper.exam.ExamMapper;
import com.ly.friend.mapper.user.UserExamMapper;
import com.ly.friend.service.user.IUserExamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserExamService implements IUserExamService {

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private UserExamMapper userExamMapper;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ExamCacheManager examCacheManager;

    @Value("${jwt.secret}")
    private String secret;

    private UserCacheManager userCacheManager;

    @Override
    public int enter(String token, Long examId) {

//        获取当前用户的信息  status
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
//        UserVO user = userCacheManager.getUserById(userId);
//        if (user.getStatus()==0){
//            throw new ServiceException(ResultCode.FAILED_USER_BANNED);
//        }

        //使用spring aop

//报名是否符合条件 (1.用户处于登录状态 2.不能报名不存在的竞赛 3.不能重复报名 4.已经开赛的禁止报名)
        Exam exam = examMapper.selectById(examId);
        if(exam==null){
            throw new ServiceException(ResultCode.EXAM_RESULT_NOT_EXIST);
        }
        if(exam.getStartTime().isBefore(LocalDateTime.now())){
            throw new ServiceException(ResultCode.EXAM_IS_START);
        }
//        Long userId= tokenService.getUserId(token,secret);
//        Long userId = userId;
        UserExam userExam = userExamMapper.selectOne(new LambdaQueryWrapper<UserExam>()
                .eq(UserExam::getExamId, examId)
                .eq(UserExam::getUserId, userId));
        if(userExam!=null){
            throw new ServiceException(ResultCode.USER_EXAM_HAS_ENTER);
        }
        examCacheManager.addUserExamCache(userId, examId);
        userExam=new UserExam();
        userExam.setExamId(examId);
        userExam.setUserId(userId);
        return userExamMapper.insert(userExam);
    }

    //先查询缓存(u:e:l:用户id) 如果缓存能查询到
    //如果查询不到 数据库中再去查询  并且数据库中的数据同步给redis
    @Override
    public TableDataInfo list(ExamQueryDTO examQueryDTO) {
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        examQueryDTO.setType(ExamListType.USER_EXAM_LIST.getValue());
        Long total = examCacheManager.getListSize(ExamListType.USER_EXAM_LIST.getValue(),userId);
        List<ExamVO> examVOList;
        if(total == null || total <= 0){//缓存不存在时的处理：
            //从数据库中查询我的竞赛列表
            PageHelper.startPage(examQueryDTO.getPageNum(),examQueryDTO.getPageSize());
            examVOList = userExamMapper.selectUserExamList(userId);
            //将数据库中的数据同步给缓存
            examCacheManager.refreshCache(examQueryDTO.getType(),userId);
            //从数据库中查询
            total=new PageInfo<>(examVOList).getTotal();
        }else{//缓存存在时的处理：
            examVOList = examCacheManager.getExamVOList(examQueryDTO,userId);
            //从redis中查询,在查询时,出现异常情况,可能会重新刷新数据,这次查询用户数据的更新
//            0:代表未完赛 1:表示开始竞赛
            total = examCacheManager.getListSize(examQueryDTO.getType(),userId);
        }
//        空结果处理：
        if  (CollectionUtil.isEmpty(examVOList)){
            return TableDataInfo.empty();
        }
        //获取符合查询条件的数据总数
        //从数据库中查询数据,不是从redis中查询数据
        return TableDataInfo.success(examVOList,total);

    }
}
